/**
 * Created by jun on 15/8/14.
 */
var async = require('async');
var OrderM=require('../models/order.js');
var UserM=require('../models/modUser.js');

/*
 * 根据订单的商品列表，查询商品信息
 * 传入good对象pid，sid
 * 传出商品名称，规格名称，商品图片
 * */
var chuliOrderList = function(orderlist){
    var orderlists= new Array();

    for(var i= 0;i<orderlist.length;i++){

        var orderone=new Object();
        orderone.orderid=orderlist[i].get('orderid');
        orderone.oid=orderlist[i].get('oid');
        orderone.objeid=orderlist[i].id;
        orderone.finalAmount=orderlist[i].get('finalAmount');
        orderone.points=orderlist[i].get('point');
        orderone.status=chuliStatus(orderlist[i].get('status'));
        orderone.payway=orderlist[i].get('payway');
        orderone.paytime=orderlist[i].get('paytime');

        orderone.show_flag=1;

        //var m = parseInt(Math.abs(new Date()-new Date(orderlist[i].createdAt))/1000/60);

        //if(orderlist[i].get('payway') == '微信支付' && orderlist[i].get('status') == 1500 && m <= 30 ){
        if(orderlist[i].get('status') == 1500){
            //微信支付，并且创建时间在30分钟内，不显示去付款按钮
            orderone.show_flag=0;
        }else{
            orderone.show_flag=1;
        }

        orderone.paytimestr=new Date(parseInt(orderlist[i].get('paytime'))).toLocaleString();
        if(!orderlist[i].get('address')){
            continue;
        }
        orderone.address=orderlist[i].get('address').address;
        orderone.name=orderlist[i].get('address').name;

        orderone.goods=new Array();
        var ordergoods=orderlist[i].get('goods');
        for(var j=0;j<ordergoods.length;j++){
            var good=new Object();
            good.pid=ordergoods[j].pid;

            if(!ordergoods[j].pname){
                good.pname='商品名称';
            }else{
                good.pname=ordergoods[j].pname;
            }
            good.sid=ordergoods[j].sid;

            if(!ordergoods[j].sname){
                good.sname='未获取';
            }else{
                good.sname=ordergoods[j].sname;
            }

            good.size=ordergoods[j].size;
            good.price=ordergoods[j].price;

            if(!ordergoods[j].img){
                good.img='#';
            }else{
                good.img=ordergoods[j].img;
            }
            orderone.goods[j]=good;
        }
        orderlists.push(orderone);
    }
    return orderlists;
};

var chuliStatus=function(status){
    var stu='';
    switch (status){
        case -1:
            stu='用户撤销';
            break;
        case -2:
            stu='平台撤销';
            break;
        case 1000:
            stu='待付款';
            break;
        case 8000:
            stu='待收货';
            break;
        case 9000:
            stu='待评价';
            break;
        case 9999:
            stu='已完成';
            break;
        default :
            stu='处理中';
            break;
    }
    return stu;

};

module.exports={
    /*
    * 获取用户订单
    * 传入uid
    * 传入订单类型
    * 返回订单列表
    * */
    //todo


    /*
    * 根据不同订单状态获取
    * 传入uid
    * 传入订单类型
    * 传入订单状态
    * 返回订单列表
    * */
    //todo
    getOrdersByType:function(req,res,next){
        var ordertype=req.params.orderType;
        var uid=req.AV.user.id;
        //var uid='55ebd59860b2ce30e834b9b5';
        switch (ordertype){
            case '0'://全部订单
                //res.render('user/history',{getorderurl:'/user/nghistory/0',title:'全部订单'});
                OrderM.getOrderListByAll(uid).then(function(orderlist){
                    var orderlists=chuliOrderList(orderlist);
                    res.render('order/myOrderByAll',{listtype:orderlists,title:'订单记录'});
                });
                break;
            case '1'://未付款
                //res.render('user/history',{getorderurl:'/user/nghistory/1',title:'未付款订单'});
                OrderM.getOrderListByPay(uid).then(function(orderlist){
                    var orderlists=chuliOrderList(orderlist);
                    res.render('order/myOrderByPay',{listtype:orderlists,title:'订单记录'});
                });
                break;
            case '3'://我的待收货订单
                //res.render('user/history',{getorderurl:'/user/nghistory/3',title:'待收货订单'});
                OrderM.getOrderListByReceived(uid).then(function(orderlist){
                    var orderlists=chuliOrderList(orderlist);
                    //var reslll= {listtype:orderlists};
                    //res.json(reslll);
                    res.render('order/myOrderByReceived',{listtype:orderlists,title:'订单记录'});
                });
                break;
            case '4'://我的待评价订单
                //res.render('user/history',{getorderurl:'/user/nghistory/4',title:'待评价订单'});
                OrderM.getOrderListByEvaluation(uid).then(function(orderlist){
                    var orderlists=chuliOrderList(orderlist);
                    res.render('order/myOrderByEvaluation',{listtype:orderlists,title:'订单记录'});
                });
                break;
            case '5'://我的已完成订单
                res.render('user/history',{getorderurl:'/user/nghistory/5',title:'已完成订单'});
                //OrderM.getOrderListByComplete(uid).then(function(orderlist){
                //    var orderlists=chuliOrderList(orderlist);
                //    res.render('user/history',{listtype:orderlists,title:'订单记录'});
                //})
                break;
        }
    },

    /*
     * 根据不同订单状态获取d订，页面中的n－repeat专用
     * 传入uid
     * 传入订单类型
     * 传入订单状态
     * 返回订单列表
     * */
    //todo
    getOrdersByTypeNG:function(req,res,next){
        var ordertype=req.params.orderType;

        var uid=req.AV.user.id;
        //var uid='55ebd59860b2ce30e834b9b5';
        switch (ordertype){
            case '0'://全部订单
                OrderM.getOrderListByAll(uid).then(function(orderlist){

                    var orderlists=chuliOrderList(orderlist);
                    var reslll= {listtype:orderlists};
                    res.json(reslll);
                });
                break;
            case '1'://未付款
                OrderM.getOrderListByPay(uid).then(function(orderlist){

                    var orderlists=chuliOrderList(orderlist);
                    var reslll= {listtype:orderlists};
                    res.json(reslll);
                });
                break;
            case '3'://我的待收货订单
                OrderM.getOrderListByReceived(uid).then(function(orderlist){

                    var orderlists=chuliOrderList(orderlist);
                    var reslll= {listtype:orderlists};
                    res.json(reslll);
                });
                break;
            case '4'://我的待评价订单
                OrderM.getOrderListByEvaluation(uid).then(function(orderlist){

                    var orderlists=chuliOrderList(orderlist);
                    var reslll= {listtype:orderlists};
                    res.json(reslll);
                });
                break;
            case '5'://我的已完成订单
                OrderM.getOrderListByComplete(uid).then(function(orderlist){
                    var orderlists=chuliOrderList(orderlist);
                    var reslll= {listtype:orderlists};
                    res.json(reslll);
                });
                break;
        }
    },




    /*
    * 进入我的会员页面，获取会员相关信息
    * 传入openid
    * 返回头像，等级，折扣，加入时间
    * */
    getUserInfo:function(req,res,next){
        var openid = req.AV.user.get('openid');
        var user=new Object();
        try{
            async.waterfall([
                function(callback){
                    UserM.getLevelByOpenID(openid).then(function(level_id){
                        user.level_id=level_id;
                        callback(null,level_id);
                    })
                },
                function(level_id,callback){

                    //UserM.getLevelInfo(''+user.level_id).then(function(levelinfo){
                    //    user.levelname=levelinfo.get('name');
                    //    var disc=levelinfo.get('discount');
                    //    switch (disc){
                    //        case '1.00':
                    //            user.discount='暂无'
                    //            break;
                    //        case '0.95':
                    //            user.discount='九五折'
                    //            break;
                    //        case '0.92':
                    //            user.discount='九二折'
                    //            break;
                    //        case '0.90':
                    //            user.discount='九折'
                    //            break;
                    //        case '0.85':
                    //            user.discount='八五折'
                    //            break;
                    //        default :
                    //            user.discount='无';
                    //            break;
                    //    }
                    //    callback(null,levelinfo);
                    //});
                    user.levelname=global.initData.level[user.level_id].name;
                    var disc=global.initData.level[user.level_id].discount;
                        switch (disc){
                            case '1.00':
                                user.discount='暂无'
                                break;
                            case '0.95':
                                user.discount='九五折'
                                break;
                            case '0.92':
                                user.discount='九二折'
                                break;
                            case '0.90':
                                user.discount='九折'
                                break;
                            case '0.85':
                                user.discount='八五折'
                                break;
                            default :
                                user.discount='无';
                                break;
                        };
                    callback(null,user);
                },
                function(user,callback){
                    UserM.getUserHeadIMG(openid).then(function(headimg){
                        user.headimg=headimg;
                        callback(null,headimg);
                    })
                },
                function(headimg,callback){
                    UserM.getUserJoinTime(openid).then(function(jointime){
                        user.jointime=jointime;
                        callback(null,jointime);
                    })
                },
                function(jointime,callback){
                    UserM.getbdPhone(openid).then(function(bdp){
                        if(!bdp){
                            bdp='未绑定手机哦';
                        }else if(bdp.length>0){
                            var qiansan=bdp.substring(0,3);
                            var housi=bdp.substring(7);
                            bdp=qiansan+'****'+housi;
                        }
                        user.bdPhone=bdp;
                        callback(null,bdp);
                    })
                }

            ],function(err,result){
                if(err){
                    //TODO:
                    return;
                }
                res.render('user/member',{user:user,title:'会员中心'});
            });

        }catch(e){
            console.log(e);
        }

    },

    /*
    * 微信支付，充值账户余额
    * 获取充值金额
    * */
    //todo

    /*
    * 充值卡，充值账户余额
    * 获取卡号
    * 获取充值卡密码
    * openid
    * */
    //todo
    updateAmountByCard:function(req,res,next){
        var openid=req.params.id;
        var cardno=req.params.cardno;
        var cardpwd=req.params.cardpwd;
        //调用models方法，充值
    },

    /*
    * 判断用户是否绑定手机
    * */
    ifBindPhone:function(req,res,next){
        var uid=req.AV.user.id;
        //调用mod
        UserM.ifBingPhone(uid).then(function(ifbind){
            res.json({bindphone:ifbind});
        })
    },
    /*
    * 绑定手机号
    * 获取手机号码
    * 获取验证码
    * openid
    * */
    bindPhone:function(req,res,next){
        var openid = req.AV.user.get('openid');
        var phone=req.params.phone;
        //调用models
        UserM.bindPhone(openid,phone).then(function(result){
            if(result){
                res.json({cgBindPhone:true});//返回绑定手机成功
            }else{
                res.json({cgBindPhone:false});
            }
        });

    },
    getLevelByOpenID:function(req,res,next){
        //我的全部订单

        //var userid = req.params.userid;         //获取用户编号
        var uid=req.AV.user.id;
        //var userid = "55ed00ec60b2ce30e84beaa5";

        UserM.getLevelByOpenID(uid).then(function(result){
            res.render('order/myOrderByAll',{title:'用户等级',result:result});
        }).catch(function(err){
            res.error(err);
        });
    },

    /*
    * 根据orderno获取订单详情
    * */
    getOrderInfo:function(req,res,next){
        var orderno=req.params.orderno;
        var uid=req.AV.user.id;
        //var uid='55ebd59860b2ce30e834b9b5';
        OrderM.getOrderDetail(uid,orderno).then(function(result){
            //var orderinfo=new Object();
            res.render('order/OrderDetail',{title:'订单详情',orderInfo:result});
        }).catch(function(err){
            res.error(err);
        })

    },
    /*
    * 确认收货
    * */
    shouhuo:function(req,res,next){

        var orderid=req.params.orderid;
        var uid=req.AV.user.id;
        OrderM.setOrderConfirm(uid,orderid).then(function(result){
            var fanhui={baocun:11};
            res.json(fanhui);
        }).catch(function(err){
            res.error(err);
        })
    },

    /*
    * 添加用户余额充值订单
    * */
    chongZhiOrder:function(req,res,next){
        var orderid=req.params.orderid;
        var amount=req.params.amount;
        var uid=req.AV.user.id;
        //添加一个余额订单
        UserM.chongZhi(orderid,uid,amount).then(function(result){
            res.json(result);
        }).catch(function(err){
            res.json(err);
        })


    },

    /*
    * 页面跳充值页面
    * */
    chongZhiUrl:function(req,res,next){
        res.render('user/chongzhi',{title:'余额充值'});
    },


    minusAmount:function(req,res,next){
        //扣除余额

        //var userid = req.params.userid;         //获取用户编号
        //var userid = "55ece38cddb263b55d4ea514";
        var uid=req.AV.user.id;
        var je = 0.1;
        UserM.minusAmount(uid,je).then(function(result){
            res.render('',{title:'用户等级',result:result});
        }).catch(function(err){
            res.error(err);
        });
    },
    updatePoints:function(req,res,next){
        //用户积分增加

        //var userid = req.params.userid;         //获取用户编号
        //var userid = "55ece38cddb263b55d4ea514";
        var uid=req.AV.user.id;
        var point = 3;
        UserM.updatePoints(uid,point).then(function(result){
            res.render('',{title:'用户等级',result:result});
        }).catch(function(err){
            res.error(err);
        });
    },
    getPoints:function(req,res,next){
        //用户积分增加

        //var userid = req.params.userid;         //获取用户编号
        //var userid = "55ece38cddb263b55d4ea514";
        var uid=req.AV.user.id;
        UserM.getPoints(uid).then(function(result){
            res.render('',{title:'用户等级',result:result});
        }).catch(function(err){
            res.error(err);
        });
    },

    /*
    * 订单评价
    * */
    pinjia:function(req,res,next){
        var orderid=req.params.orderid;
        var uid=req.AV.user.id;
        OrderM.getOrderDetail(uid,orderid).then(function(result){
            res.render('user/evaluation',{title:'订单评价',orderInfo:result});
        }).catch(function(err){
            res.error(err);
        })
    },

    /*
    * 保存评价
    * */
    savePinJia_old:function(req,res,next){
        var obpinjia = new Object();
        obpinjia.orderid=req.params.orderid;
        obpinjia.content=req.params.content;
        obpinjia.uid=req.AV.user.id;
        obpinjia.username=req.AV.user.get('nickname');
        obpinjia.phone=req.AV.user.get('mobilePhoneNumber');
        obpinjia.pid=req.params.pid;
        obpinjia.pname=req.params.pname;
        obpinjia.score=parseInt(req.params.score||5);
        obpinjia.syncStatus=1;
        obpinjia.applystatus=0;
        obpinjia.status=1;
        OrderM.addEvaluation(obpinjia,obpinjia.uid,obpinjia.orderid).then(function(result){
            res.json({spinjia:true});//评价保存成功
            //res.render('user/history/4',{title:'订单评价'});
        }).catch(function(err){
            res.json({spinjia:false});//评价保存失败
            //res.error(err);
        })
    },

    savePinJia:function(req,res,next){
        //var obpinjia = JSON.parse(req.query.goods);

        var pinjia = JSON.parse(req.query.goods);
        var user = {uid:req.AV.user.id,username:req.AV.user.get('nickname'),phone:req.AV.user.get('mobilePhoneNumber')}

        OrderM.addEvaluation(pinjia,user).then(function(result){
            res.json({spinjia:true});//评价保存成功
            //res.render('user/history/4',{title:'订单评价'});
        }).catch(function(err){
            res.json({spinjia:false});//评价保存失败
            //res.error(err);
        })
    },

    /*
    * 判断用户是否绑定手机，根据查询结果，返回不同值
    * 返回bpfalse，未绑定
    * 返回bptrue，已绑定，修改绑定手机
    * */
    judgeBindPhone:function(req,res,next){
        var uid=req.AV.user.id;
        //调用mod
        UserM.ifBingPhone(uid).then(function(ifbind){
            if(ifbind.ifbdp){
                res.render('user/bindPhone',{title:'绑定手机',lbdp:ifbind.bdp});
            }else{
                res.render('user/bindPhone',{title:'绑定手机',lbdp:'bind'});
            }
        })
    },

    /*
    * 根据传入的值，返回不同参数
    * szpwd，设置支付密码
    * xgpwd，修改支付密码
    * zhpwd，找回支付密码
    * */
    handlePWD:function(req,res,next){
        var djpwd=req.params.pwdtype;
        if(djpwd=='sz'){
            res.render('user/password',{title:'设置支付密码',jpwd:'sz'});
        }else if(djpwd=='xg'){
            res.render('user/password',{title:'设置支付密码',jpwd:'xg'});
        }else if(djpwd=='zh'){
            res.render('user/password',{title:'设置支付密码',jpwd:'zh'});
        }
    },

    /*
    * 向指定手机发送验证码
    * */
    sendsmscode:function(req,res,next){
        var phone=req.params.phone;
        UserM.sendsmsphone(phone).then(function(result){
            if(result){
                res.json({sendsms:true});
            }else{
                res.json({sendsms:false});
            }
        })
    },


    //验证验证码，保存绑定手机号码
    j:function(req,res,next) {
        var openid = req.AV.user.get('openid');
        var data=req.query;
        UserM.yzsmscode(data.lcode,data.lphone,openid).then(function(result){
            if(result){
                res.json({ifsmscode:true});
            }else{
                res.json({ifsmscode:false});
            }
        })
    },

    //验证更换手机号发送的验证码
    ghphone:function(req,res,next) {
        var data=req.query;
        var scode=data.scode;
        var oldphone=data.oldphone;
        UserM.yzghsmsmcode(scode,oldphone).then(function(result){
            if(result){
                res.json({ifsmscode:true});
            }else{
                res.json({ifsmscode:false});
            }
        })
    },

    /*
    * 验证用户是否已经设置支付密码
    * */
    ifSetpwd:function(req,res,next){
        var uid=req.AV.user.id;
        UserM.ifSetpwd(uid).then(function(password){
            if(typeof(password) != 'undefined'){
                if(password.length==6){
                    res.json({ifset:true})
                }else{
                    res.json({ifset:false})
                }
            }else{
                res.json({ifset:false})
            }
        })
    },

    /*
    * 保存支付密码
    * */
    saveyepwd:function(req,res,next){
        var uid=req.AV.user.id;
        var data=req.query;
        var yepwd=data.yepwd;
        UserM.saveyepwd(uid,yepwd).then(function(result){
            if(result){
                res.json({savebool:true})
            }else{
                res.json({savebool:false});
            }
        })
    },

    /*
    * 修改支付密码
    * */
    reSetpwd:function(req,res,next){
        var data = req.query;
        var ypwd=data.ypwd;
        var qrxpwd=data.qrxpwd;
        var uid=req.AV.user.id;
        UserM.reSetpwd(ypwd,qrxpwd,uid).then(function(result){
            if(result.pwdres=='pwd'){
                res.json({ppwdres:'pwd'})
            }else if(result.pwdres=='cwpwd'){
                res.json({ppwdres:'cwpwd'})
            }else if(result.pwdres=='ypwd'){
                res.json({ppwdres:'ypwd'})
            }
        })
    },

    /*
    * 验证支付密码是否正确
    * */
    jarpassword:function(req,res,next){
        var uid=req.AV.user.id;
        var data = req.query;
        var password = data.password;
        UserM.ifSetpwd(uid).then(function(passw){
            if(password==passw){
                res.json({rightpwd:true})
            }else{
                res.json({rightpwd:false})
            }
        })
    },
    //向找回密码的绑定手机发送验证码
    findpwd:function(req,res,next){
        var uid=req.AV.user.id;
        UserM.findcode(uid).then(function(send){
            if(send.bdphone && send.sendcode){
                res.json({send:'sendcode'});
            }else if(!send.bdphone){
                res.json({send:'bdpw'});
            }else if(!send.bdPhone&&send.sendcode){
                res.json({send:'failed'});
            }
        })
    },
    //保存通过手机验证的密码
    savewjpwd:function(req,res,next){
        var data = req.query;
        var code = data.code;
        var zhpwd =  data.zhpwd;
        var uid=req.AV.user.id;
        UserM.savezhpwd(code,zhpwd,uid).then(function(result){
            if(result.vcode&&result.setpwd){
                res.json({setpwd:true})
            }else if(!result.vcode){
                res.json({setpwd:false})
            }
        })
    }

}